import React, {
  useCallback,
  useEffect,
  useImperativeHandle,
  useState,
} from 'react';
import { Form, Input, TreeSelect, InputNumber, Row, Col } from 'antd';

import { positionAPI } from '../../type';

import cls from 'classnames';
import pageStyles from '@/common/pageLayout.less';

// import '../../styles.less';
import MyIcon from '@/components/MyIcon';

export const FirstStep = React.forwardRef<
  positionAPI.IStepRef,
  positionAPI.IFistStepProps
>(
  (
    {
      // display,
      pidPosList, //渲染上级岗位数据
      recordPosForm, //填写的数据 或者编辑传入的数据
      detailInfoData,
    },
    ref,
  ) => {
    const [form] = Form.useForm();

    // let defaultInfo = recordPosForm
    const [defaultInfo, setDefaultInfo] = useState<any>(); //保存详情数据

    useImperativeHandle(ref, () => ({
      form: form,
    }));

    useEffect(() => {
      if (recordPosForm && JSON.stringify(recordPosForm) != '{}') {
        // form?.setFieldsValue({
        //   name: recordPosForm?.name,
        //   description: recordPosForm?.description,
        //   pID: recordPosForm?.pID,
        //   seq: recordPosForm?.seq,
        //   remark: recordPosForm?.remark
        // })
        form?.setFieldsValue(recordPosForm);
      } else if (detailInfoData && JSON.stringify(detailInfoData) != '{}') {
        // form?.setFieldsValue({
        //   name: detailInfoData?.name,
        //   description: detailInfoData?.description,
        //   pID: detailInfoData?.pID,
        //   seq: detailInfoData?.seq,
        //   remark: detailInfoData?.remark
        // })
        form?.setFieldsValue(detailInfoData);
      }
    }, [recordPosForm, detailInfoData]);

    // 保存上级岗位搜索输入框的值
    const [treeSearch, setTreeSearch] = useState<string>('');

    // 处理树数据
    const orgTreeData = (data: any[]): any[] => {
      return data?.map((item: any) => {
        const name = item?.name;
        const nameLength = name?.length;
        const select = name?.search(treeSearch);
        const searchLength = treeSearch?.length;
        const afterStr = name?.slice(0, select);
        const selectStr = treeSearch;
        const beforeStr = name?.slice(select + searchLength, nameLength);
        const titleTree =
          select > -1 && selectStr ? (
            <span className={pageStyles['over-flow-hidden']}>
              {afterStr}
              <span style={{ color: '#f50' }}>{selectStr}</span>
              {beforeStr}
            </span>
          ) : (
            <span className={pageStyles['over-flow-hidden']}>{item?.name}</span>
          );

        if (item?.children && item?.children?.length > 0) {
          return {
            ...item,
            title: (
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  paddingRight: 20,
                }}
                id={item?.id}
              >
                {getTreeIcon(String(item?.category))}
                {titleTree}
              </div>
            ),
            searchTitle: item?.name,
            key: item?.id,
            value: item?.id,
            children: orgTreeData(item?.children),
          };
        }
        return {
          ...item,
          title: (
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                paddingRight: 20,
              }}
              id={item?.id}
            >
              {getTreeIcon(String(item?.category))}
              {titleTree}
            </div>
          ),
          searchTitle: item?.name,
          key: item?.id,
          value: item?.id,
        };
      });
    };

    // 判断岗位类型的图标
    const getTreeIcon = (category: string) => {
      switch (category) {
        case '0':
          return (
            <MyIcon
              style={{ marginRight: 5, color: '#4d83f5' }}
              type="icon-bank"
            />
          );
        case '1':
          return (
            <MyIcon
              style={{ marginRight: 5, color: '#4d83f5' }}
              type="icon-cluster"
            />
          );
        default:
          return (
            <MyIcon
              style={{ marginRight: 5, color: '#4d83f5' }}
              type="icon-cluster"
            />
          );
      }
    };

    // 获取搜索框输入的值
    const treeSearchValue = useCallback(
      (valText: string) => {
        setTreeSearch(valText);
      },
      [treeSearch],
    );

    return (
      <div
        // style={{ display: 'flex', justifyContent: 'center', height: '100%', width: '100%' }}
        className={cls('update-step-layout', pageStyles['fromView-styles'])}
      >
        <Form
          // labelCol={{
          //   span: 4,
          // }}
          // wrapperCol={{
          //   span: 20,
          // }}
          // style={{
          //   width: '80%',
          // }}
          form={form}
          layout="inline"
        >
          <Row>
            <Col span={24}>
              <Form.Item
                label="岗位名称"
                name="name"
                rules={[
                  {
                    required: true,
                    message: '请输入岗位名称',
                  },
                ]}
                initialValue={defaultInfo?.name}
              >
                <Input placeholder="请输入岗位名称" allowClear />
              </Form.Item>
            </Col>

            <Col span={24}>
              <Form.Item
                label="岗位描述"
                name="description"
                rules={[
                  {
                    required: true,
                    message: '请输入岗位描述',
                  },
                ]}
                initialValue={defaultInfo?.description}
              >
                <Input.TextArea
                  placeholder="请输入岗位描述"
                  allowClear
                  showCount
                  maxLength={200}
                  autoSize={{ minRows: 2, maxRows: 4 }}
                />
              </Form.Item>
            </Col>

            <Col span={24}>
              <Form.Item
                label="上级岗位"
                name="pID"
                initialValue={defaultInfo?.pID}
              >
                <TreeSelect
                  placeholder="请输入上级岗位"
                  allowClear
                  onSearch={treeSearchValue}
                  treeNodeFilterProp={'searchTitle'}
                  showSearch={true}
                  treeData={orgTreeData(pidPosList)}
                />
              </Form.Item>
            </Col>

            <Col span={24}>
              <Form.Item
                label="序号"
                name="seq"
                rules={[
                  {
                    required: true,
                    message: '请输入序号',
                  },
                ]}
                initialValue={defaultInfo?.seq ?? 0}
              >
                <InputNumber placeholder="请输入序号" min={0} />
              </Form.Item>
            </Col>

            <Col span={24}>
              <Form.Item
                label="备注"
                name="remark"
                initialValue={defaultInfo?.remark}
              >
                <Input.TextArea
                  placeholder="请输入备注"
                  style={{ width: '100%' }}
                  allowClear
                  showCount
                  maxLength={100}
                  autoSize={{ minRows: 2, maxRows: 4 }}
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </div>
    );
  },
);
